import { Card, Form, Input, Button, message } from 'antd';
import './index.scss';
import * as userApi from '../../api/user';
import store from '../../redux';

const Login = ({ history, ...props }) => {
    /**
     * 提交表单，触发的事件
     */
    const onFinish = async (values) => {
        const res = await userApi.login(values);
        // 登录失败
        if (res.code !== 200) {
            message.error(res.message);
            return;
        }
        console.log('res.data', res.data);
        // 登录成功，保存登录态
        store.dispatch({ type: 'loginSuccess', payload: res.data });
        // window.sessionStorage.setItem('token', res.data.token);
        // window.sessionStorage.setItem(
        //     'profile',
        //     JSON.stringify(res.data.profile)
        // );
        // window.sessionStorage.setItem('menus', JSON.stringify(res.data.menus));
        // 登录态保存成功，跳转到后台首页
        history.push('/admin/dashboard');
    };

    /**
     * 提交表单失败触发的事件
     */
    const onFinishFailed = () => {
        console.log('触发了失败回调');
    };

    return (
        <div className="login-page">
            <div className="container">
                <Card title="登录 RBAC 成绩管理系统" hoverable>
                    <Form
                        name="basic"
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                    >
                        <Form.Item
                            name="mobile"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入手机号',
                                },
                            ]}
                        >
                            <Input placeholder="请输入手机号" />
                        </Form.Item>

                        <Form.Item
                            name="password"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入密码',
                                },
                            ]}
                        >
                            <Input.Password placeholder="请输入密码" />
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit" block>
                                登录系统
                            </Button>
                        </Form.Item>
                    </Form>
                </Card>
            </div>
        </div>
    );
};

export default Login;
